/**
 * 订单管理-订单查询
 * 
 * @author mouwanming
 */
var queryVoucherOrderSearch = function() {
	var queryVoucherOrdersFieldSet = new Ext.form.FieldSet({
		id : 'queryVoucherOrdersFieldSet',
		title : '查询条件',
		collapsible : true,// 可折叠
		buttonAlign : 'center',
		keys : [{
					key : 13, // 13代表回车
					fn : queryVoucherOrders,
					scope : this
				}],
		items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '用户编号',
											name : "userId"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '收货人手机号',
											name : "consignPhone"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '收货人',
											name : "consignee"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '收货人地址',
											name : "consignAddress"
										}]
							}]
				}, {
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : 'voucherOrderManager_id',
											xtype : 'numberfield',
											anchor : '100%',
											fieldLabel : '订单编号',
											name : "id",
											allowDecimals : false,
											allowNegative : false
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : "voucherOrderManager_voucherCode",
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '抵用券编号',
											name : "voucherCode"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : 'voucherOrderManager_orderStatusMultiCmb',
											xtype : 'dataDictionaryMultiCmb',
											anchor : '100%',
											fieldLabel : "订单状态",
											editable : false,
											autoLoad : false,
											hiddenValueId:'voucherOrderManager_voucherOrderStatus',
											dictionaryType : PmsUtil.order_vf_status
										}]
							}, {
								id : 'voucherOrderManager_voucherOrderStatus',
								xtype : 'hidden',
								name : 'orderStatusIds'
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'dataDictionaryCmb',
											anchor : '100%',
											fieldLabel : "支付方式",
											editable : false,
											autoLoad : false,
											existall : true,
											multiSelect : true,
											defaultFirstRow : 1,
											hiddenName : 'payWays',
											dictionaryType : PmsUtil.orders_pay_type
										}]
							}]
				}, {
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 70,
												handler : function() {
													queryVoucherOrders();
												},
												style : {
													marginLeft : "100px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 70,
												handler : function() {
													queryVoucherOrderForm.getForm()
															.reset();
													Ext
															.getCmp("voucherOrderManager_orderStatusMultiCmb")
															.reset();
												}
											}]
								}]
							},{
							}]
				}]
	});
	fieldSetListeners(['queryVoucherOrdersFieldSet', 'queryVoucherOrderForm',
					'VoucherOrderManagerGrid'], [0.26, 0.74]);

	var queryVoucherOrderForm = new Ext.form.FormPanel({
				id : 'queryVoucherOrderForm',
				anchor : '100% 26%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryVoucherOrdersFieldSet]
			});
	return queryVoucherOrderForm;
};

/**
 * grids
 */

var voucherOrderManagerGrid = function() {
	var voucherOrderManagerSm = new Ext.grid.CheckboxSelectionModel();// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var voucherOrderManagerCm = new Ext.grid.ColumnModel([voucherOrderManagerSm,
			new Ext.grid.RowNumberer(), {
				dataIndex : "id",
				header : "订单编号",
				sortable : false,
				width : 70
			}, {
				dataIndex : "voucherCode",
				header : "抵用券编号",
				sortable : false,
				width : 160,
				renderer : function(value, cellmeta, record, rowIndex,
						columnIndex, store) {
					var returnValue = "";
					var orderId = record.data.id;
					if (value) {
						returnValue = '<a href ="#" onClick="lookOrderManagerDetail(\''
								+ orderId + '\')">' + value + '</a>';
					}
					return returnValue;
				}
			}, {
				dataIndex : "userId",
				header : "用户编号",
				sortable : false,
				width : 70
			}, {
				dataIndex : "userName",
				header : "用户姓名",
				sortable : false,
				width : 70
			}, {
				dataIndex : "voucherPaymentId",
				header : "支付流水号",
				sortable : false,
				width : 80
			}, {
				dataIndex : "orderStatus",
				header : "订单状态",
				sortable : false,
				width : 60,
				renderer : function(value) {
					return PmsUtil.VoucherOrderStatus(value);
				}
			}, {
				dataIndex : "payWays",
				header : "支付方式",
				sortable : false,
				width : 60,
				renderer : function(value) {
					return PmsUtil.PayType(value);
				}
			}, {
				dataIndex : "payDate",
				header : "支付时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "voucherNumber",
				header : "商品数量",
				sortable : false,
				width : 70
			}, {
				dataIndex : "totalAmount",
				header : "订单总金额",
				sortable : false,
				width : 70,
				renderer : function(val) {
					return PmsUtil.Price(val);
				}
			}, {
				dataIndex : "payAmount",
				header : "实际支付金额",
				sortable : false,
				width : 90,
				renderer : function(val) {
					return PmsUtil.Price(val);
				}
			}, {
				dataIndex : "consignee",
				header : "收货人",
				sortable : false,
				width : 70
			}, {
				dataIndex : "consignPhone",
				header : "收货人电话",
				sortable : false,
				width : 100
			}, {
				dataIndex : "consignAddress",
				header : "收货人地址",
				sortable : false,
				width : 130,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="收货人地址:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "remark",
				header : "备注",
				sortable : false,
				width : 100,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="备注:" ext:qtip="' + value + '"';
						return value;
					}
				}
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : false,
				width : 70
			}, {
				dataIndex : "deliveryPicture",
				header : "确认发货抵用券图片",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);

				}
			},{
				header : "管理",
				width : 100,
				dataIndex : "id",
				renderer : function(j, i, g, m, h) {
					var orderId = g.data.id;
					var k = "";
					if (isGranted("voucherOrderManager_物流状态")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="managerLookLogisticStatus('
								+ orderId + ')\">物流状态</a>';
					}
					return k;
				}
			}]);

	// 定义分析器
	var voucherOrderManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "voucherCode"
						}, {
							name : "userId"
						}, {
							name : "userName"
						}, {
							name : "voucherPaymentId"
						}, {
							name : "orderStatus"
						}, {
							name : "payDate"
						}, {
							name : "payWays"
						},{
							name : "totalAmount"
						}, {
							name : "voucherNumber"
						}, {
							name : "payAmount"
						}, {
							name : "couponFee"
						}, {
							name : "couponSource"
						}, {
							name : "consignee"
						}, {
							name : "consignPhone"
						}, {
							name : "consignAddress"
						}, {
							name : "remark"
						}, {
							name : "createdDate"
						}, {
							name : "createdName"
						}, {
							name : "updatedDate"
						}, {
							name : "updatedName"
						}, {
							name : "logisticNo"
						}, {
							name : "deliveryPicture"
						}]
			});

	// 取数据store
	var voucherOrderViewStore = new Ext.data.Store({
//				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/voucherManager/selectVoucherOrders"
						}),
				remoteSort : true,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryVoucherOrderForm').getForm()
											.getValues());
						}
					}
				},
				reader : voucherOrderManagerReader
			});
	voucherOrderViewStore.setDefaultSort("vo.id", "desc");
	var voucherOrderManagerTb = new Ext.Toolbar({// 定义grid的toolbar
		height : 25,
		items : []
	});

	voucherOrderManagerTb.add(new Ext.scm.Button({
				text : "导出excel",
				iconCls : "btn-excel",
				width : 80,
				pressed : true,
				hsValue : "voucherOrderManager_批量导出",
				listeners : {
					"click" : function() {
						exportVoucherOrdersToExcel();
					}
				}
			}));

	voucherOrderManagerTb.add(new Ext.Toolbar.Spacer());
	voucherOrderManagerTb.add(new Ext.scm.Button({
				text : "刷 新",
				width : 80,
				iconCls : "btn-refresh",
				hsValue : "voucherOrderManager_刷新",
				pressed : true,
				handler : function() {
					queryVoucherOrders();
				}
			}));

	var voucherOrderManagerGrid = new Ext.grid.GridPanel({
				id : 'voucherOrderManagerGrid',
				store : voucherOrderViewStore,
				cm : voucherOrderManagerCm,
				sm : voucherOrderManagerSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 74%',
				frame : true,
				tbar : voucherOrderManagerTb,
				bbar : new PG.PagingBar({
							store : voucherOrderViewStore,
							isShowTwoHunder : true
						})
			});
	return voucherOrderManagerGrid;
};

/**
 * 查询物流状态列表
 * 
 * @param {}
 *            id
 */
function managerLookLogisticStatus(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.LOGISTIC_STATUS);
	var createNewTab = new CreatNewTab(PmsUtil.LOGISTIC_STATUS, '物流状态');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['logisticStatusGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/voucher/logisticStatus.js'], function() {
		Ext.getCmp("centerTabPanel").getActiveTab().add(logisticStatusGrid(id));
		Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
	});
}

// 查询
function queryVoucherOrders() {
	var grid = Ext.getCmp("voucherOrderManagerGrid");
	var form = Ext.getCmp("queryVoucherOrderForm");
	if (form.getForm().isValid()) {
		grid.getStore().load();
	}
}

// 修改
function updateVoucherOrder(orderId) {
	try {
		updateVoucherOrderWin(orderId).show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/voucher/voucherOrderForm.js'], function() {
			updateVoucherOrderWin(orderId).show();
				});
	}
}

// 发货
function stockSend(orderId) {
	try {
		stockSendWin(orderId).show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/voucher/stockSendForm.js'], function() {
					stockSendWin(orderId).show();
				});
	}

}


/**
 * 查看订单详情
 * 
 * @param {}
 *            id
 */
function lookVoucherOrderManagerDetail(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.ORDER_MESSAGE_DETAIL);
	var createNewTab = new CreatNewTab(PmsUtil.ORDER_MESSAGE_DETAIL, '订单详情');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['lookVoucherOrderDetailFields',
						'lookVoucherOrderDetailForm', 'lookVoucherOrderDetailGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/voucher/voucherOrderDetail.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						lookOrderDetailSearch(id), orderDetailGrid(id));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}

// 订单的excel导出
function exportVoucherOrdersToExcel() {
	var d = Ext.getCmp("voucherOrderManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要导出的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}

	var orderIds = "";
	var m = 0;
	for (var i = 0; i < jsonrecord.length; i++) {
		var tmp = jsonrecord[i];
		if (m > 0) {
			orderIds = orderIds + "," + tmp.data.id;
		} else {
			orderIds = tmp.data.id;
		}
		m++;
	}
	Ext.Msg.confirm("信息确认", "是否批量导出订单数据？", function(btn) {
				if (btn == 'yes') {
					document.location.href = __ctxPath
							+ "/voucherManager/exportOrdersToExcel?orderIds="
							+ orderIds;
				}

			});
};
/**
 * 公共获取时间
 * 
 * @param {}
 *            AddDayCount
 * @return {}
 */
function GetDateStr(AddDayCount) {
	var s;
	var systemDate = new Date();
	systemDate.setDate(systemDate.getDate() + AddDayCount);// 获取AddDayCount天后的日期
	s = systemDate.getFullYear() + "-"; // 取年份
	var strMonth = (systemDate.getMonth() + parseInt(1)).toString();
	s = s + ((strMonth.length == 1) ? ("0" + strMonth) : strMonth) + "-";// 取月份
	var strDate = systemDate.getDate().toString();
	s += ((strDate.length == 1) ? ("0" + strDate) : strDate) + " ";// 取日期
	return s;
}
/**
 * 获取昨天日期
 */
function getYesterdayDate() {
	return GetDateStr(-1) + "16:00:00";
}

/**
 * 当前时间
 * 
 * @return {}
 */
function getTodayDate() {
	return GetDateStr(0) + "16:00:00";
};

Ext.getCmp("centerTabPanel").getActiveTab().add(queryVoucherOrderSearch(),
		voucherOrderManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
